package com.voda.mail.impl;

import java.io.StringWriter;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.lang.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;

import com.voda.entity.User;
import com.voda.mail.config.EmailSender;
import com.voda.mail.core.EmailTypeEnum;

/**
 * The Class AbstractEmailService.
 */
public abstract class AbstractEmailService {
	
	/** The Constant EMAIL_ADDRESS. */
	protected static final String EMAIL_PERSONAL = "Cities Talking";
	
	protected static final String EMAIL_ADDRESS = "ctaptestdemo@mail.ru";
	
	protected static final String EMAIL_PASSWORD = "ctap_demo73!";

	
    /** The velocity engine. */
    @Autowired
    protected VelocityEngine velocityEngine;
    
    @Autowired
    protected EmailSender emailConfig;
    
    /**
     * Send email.
     *
     * @param attachmentPath the attachment path
     * @param attachmentName the attachment name
     * @param user the user
     * @param type the type
     */
    protected void sendEmail(final String attachmentPath, final String attachmentName, final User user, final EmailTypeEnum type, final VelocityContext context) {
		MimeMessagePreparator preparator = new MimeMessagePreparator() {
			public void prepare(MimeMessage mimeMessage) throws Exception {
				MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
				message.setTo(user.getEmail());
				message.setFrom(new InternetAddress(EMAIL_ADDRESS, EMAIL_PERSONAL));
				message.setSubject(type.getSubject());
				Template template = velocityEngine.getTemplate(type.getTemplatePath());
				StringWriter writer = new StringWriter();
				template.merge(context, writer);
				message.setText(writer.toString(), true);
				if (!StringUtils.isBlank(attachmentPath)) {
					FileSystemResource file = new FileSystemResource(attachmentPath);
					message.addAttachment(attachmentName, file);
				}
			}
		};
		this.emailConfig.getEmailSender(EMAIL_ADDRESS, EMAIL_PASSWORD).send(preparator);
	}
    
}
